package com.sensor.meter.utils

import android.util.TypedValue
import android.content.Context
import android.view.Gravity
import android.widget.Toast

/**
 * @author       CT
 * @date         2024/3/7
 * @description  Context 扩展
 */


/**
 * dp 转 px
 * @receiver View
 * @param dbVal Float
 * @return Float
 */
fun Context.dp2px(dbVal:Float):Float{
  //(dpValue * resources.displayMetrics.density + 0.5f).toInt()
  return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dbVal, resources.displayMetrics)
}

fun Context.px2dp(px:Float):Float{
 return ( px / resources.displayMetrics.density + 0.5f)
}

/**
 * sp 转 px
 * @receiver View
 * @param spVal Float
 * @return Float
 */
fun Context.sp2px(spVal:Float):Float{
  // spValue * resources.displayMetrics.scaledDensity + 0.5f
  return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, resources.displayMetrics)
}


fun Context.px2sp(pxValue: Float): Float {
  //TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,pxValue,resources.displayMetrics)
  return pxValue / resources.displayMetrics.scaledDensity + 0.5f
}

//----------toast----------
fun Context.toast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
  Toast.makeText(this, text, duration).show()
}

fun Context.toast(resId: Int, duration: Int = Toast.LENGTH_SHORT) {
  Toast.makeText(this, resId, duration).show()
}

fun Context.centerToast(resId: Int, duration: Int = Toast.LENGTH_SHORT) {
  var t = Toast.makeText(this, resId, duration)
  t.setGravity(Gravity.CENTER, 0, 0)
  t.show()
}